// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.

$(function() {
	$("input[id $='quantity']").on('change', function() {
		var quantity = $(this).val();
		var unit_price = $(this).closest('tr').find("input[id $='unit_price']").val();

		$(this).closest('tr').find("input[id $='amount']").val(cal_subtotal(quantity, unit_price));
	});

	$("input[id $='price']").change(function() {
		var unit_price = $(this).val();
		var quantity = $(this).closest('tr').find("input[id $='quantity']").val();
		$(this).closest('tr').find("input[id $='amount']").val(cal_subtotal(quantity, unit_price));
	});

	$("#new_contract_submit").on('click', function(e) {
		//prevent Default functionality
		e.preventDefault();

		var fieldname = "product_name";

		if (is_blank(fieldname)) {
			console.log(" empty! ");
			return false;
		} else {
			$("#new_contract").submit();
		}
	});

	// $("#new_contract").submit(function(e){
	// //prevent Default functionality
	// e.preventDefault();
	//
	// var fieldname= "product_name";
	//
	// if ( is_blank(fieldname) ) {
	// console.log(" empty! ");
	// return false;
	// } else {
	// $(this).submit();
	// }
	//
	// return;
	// });

});

function cal_subtotal(quantity, unit_price) {
	return quantity * unit_price;
}

// validates if the fields are empty.
// arrField: id of fields
function is_blank(field) {
	$("input[id $='" + field + "']").each(function() {
		if ($(this).val() == "") {
			$(this).focus();
			$(this).addClass("is-invalid");
			return true;
		} else {
			$(this).removeClass("is-invalid");
		}
	});
	return false;
};
